<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="shareRegister"
    @ok="confirmSubmit"
    @close="drawerReset"
    width="424"
    showFooter
    isAbsolute
    getContainer=".page-wrapper"
  >
    <div class="box-drawer">
      <BasicForm @register="shareForm" />
    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup name="shareAdd">
import { reactive, ref, computed } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { BasicForm, FormSchema, useForm } from '@/components/Form/index'
import { getShareFormConfig } from '../dataSource'
import { userStore } from '@/store/modules/user'
import { getUpdateSchemaArr } from '@/utils/formSchema'
import { operateActionType } from '@/types/enum'
import { cloneDeep } from 'lodash-es'
import { message } from 'ant-design-vue'
import api from '@/api'

const { shareAdd } = api

const emit = defineEmits(['operateSuccess', 'register'])

const userModule = userStore()
const operateActionTypeMap = operateActionType

const drawerInfo = reactive({
  type: '',
  shareId: ''
})

const shareFormConfig = getShareFormConfig()

const [shareForm, { setFieldsValue, getFieldsValue, validate, resetFields, updateSchema }] = useForm(shareFormConfig)

const [shareRegister, { closeDrawer, changeOkLoading }] = useDrawerInner(async (data) => {
  drawerInfo.type = data.type

  // 查看时表单展示
  updateSchema(getUpdateSchemaArr(shareFormConfig.schemas, data.type))
  updateSchema([
    {
      field: 'code',
      componentProps: {
        disabled: data.type !== operateActionTypeMap.ADD
      }
    }
  ])
  if (data.type !== operateActionTypeMap.ADD) {
    drawerInfo.shareId = data.record.id
    let record = cloneDeep(data.record)
    setFieldsValue({
      ...record
    })
  }
})

const drawerReset = () => {
  drawerInfo.shareId = ''
  resetFields()
  changeOkLoading(false)
}

// 提交数据
const confirmSubmit = async () => {
  try {
    await validate()
    let formValue = getFieldsValue()
    changeOkLoading(true)
    let reqParam = { ...formValue }
    if (drawerInfo.type !== operateActionTypeMap.ADD) {
      reqParam.id = drawerInfo.shareId
    }
    await shareAdd(reqParam)
    message.success(drawerInfo.type === operateActionTypeMap.ADD ? '邀请链接新增成功' : '邀请链接编辑成功')
    closeDrawer()
    drawerReset()
    emit('operateSuccess')
  } catch (error) {
    changeOkLoading(false)
  }
}
</script>

<style lang="less" scoped>
.box-drawer {
  padding: 8px 44px;
  :deep(.ant-form-item-label) {
    font-weight: 600;
  }
}
</style>
